package com.example.summary.leetcode;

import com.alibaba.fastjson.JSONObject;

/**
 * Created by wzn on 2019/5/24.
 */
public class LeetCode111 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {

        TreeNode g = new TreeNode(2, null, null);
        TreeNode h = new TreeNode(4, null, null);
        TreeNode i = new TreeNode(8, null, null);

        TreeNode d = new TreeNode(1, null, g);
        TreeNode e = new TreeNode(5, h, null);
        TreeNode f = new TreeNode(7, null, i);

        TreeNode b = new TreeNode(3, d, e);
        TreeNode c = new TreeNode(9, f, null);

        TreeNode a = new TreeNode(6, b, c);

        System.out.println(JSONObject.toJSONString(minDepth(0, a)));

    }

    public static int minDepth(TreeNode root) {
        return minDepth(0, root);
    }

    public static int minDepth(int shendu, TreeNode root) {
        if (null == root)
            return 0;

        shendu = shendu + 1;

        if (null != root.left && null != root.right) {

            int left = minDepth(shendu, root.left);
            int right = minDepth(shendu, root.right);

            if (left < right) {
                return left;
            } else {
                return right;
            }

        } else {
            if (null != root.left) {
                return minDepth(shendu, root.left);
            }

            if (null != root.right) {
                return minDepth(shendu, root.right);
            }
        }

        return shendu;
    }
}
